package message.io;

import java.io.IOException;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

import message.MessageBuilder;
import message.MessageParser;
import nrpc.exception.TimeoutException;

public class SingleRequest {
	
	private static final int TIMEOUT = 3000;
	
	/**
	 * 
	 * @param channel
	 * @param buffer
	 * @param parser
	 * @throws IOException 连接断开时抛出异常
	 */
	public static void send(SocketChannel channel, ByteBuffer buffer, MessageParser parser) throws IOException {
		long beg = System.currentTimeMillis();
		while(true) {
			parser.write(buffer);
			buffer.flip();
//			System.out.println("limit:" + buffer.limit());
			if(buffer.limit() == 0) break;
			channel.write(buffer);
			buffer.compact();
			if(System.currentTimeMillis() - beg > TIMEOUT) throw new TimeoutException("写报文超时");
		}
		buffer.compact();
	}
	
	/**
	 * 
	 * @param channel
	 * @param buffer
	 * @param builder
	 * @throws IOException 连接断开、超时则抛出异常
	 */
	public static void recv(SocketChannel channel, ByteBuffer buffer, MessageBuilder builder) throws IOException {
		channel.socket().setSoTimeout(TIMEOUT);
		long beg = System.currentTimeMillis();
		while(true) {
			buffer.flip();
			if(builder.read(buffer)) break;
			buffer.compact();
			if(channel.read(buffer) == -1) {
				throw new SocketException();
			}
//			if(buffer.limit() > 0)
//				System.out.println("recv:" + buffer.limit());
			if(System.currentTimeMillis() - beg > TIMEOUT) throw new TimeoutException("读报文超时");
		}
		buffer.compact();
//		System.out.println("leaved:" + buffer.position());
	}
	
	
}
